//
//  PBLoginViewController.m
//  PBHomeDemo
//
//  Created by Playboy on 2017/12/19.
//  Copyright © 2017年 tmkj. All rights reserved.
//

#import "PBLoginViewController.h"
#import "PBRegistViewController.h"
#import "TMTabBarViewController.h"
#import <AdSupport/AdSupport.h>
//#import "PBAES.h"
//#import "RSA.h"

@interface PBLoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (nonatomic, strong) UIButton *getCodeBtn;

@end

@implementation PBLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
}

- (void)configure {
    [self configureView];
    [self configureData];
}
- (void)configureView {
    self.view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"login_bg"].CGImage);
    self.phoneView.layer.cornerRadius = 20;
    self.phoneView.layer.borderWidth = 1.0f;
    self.phoneView.layer.borderColor = UIColorWithRGB(184, 184, 184).CGColor;
    self.codeView.layer.cornerRadius = 20;
    self.codeView.layer.borderWidth = 1.0f;
    self.codeView.layer.borderColor = UIColorWithRGB(184, 184, 184).CGColor;
    [self.phoneTextField addTarget:self action:@selector(phoneTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"获取动态密码" forState:UIControlStateNormal];
    [btn setTitleColor:UIColorWithRGB(89, 89, 89) forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [btn addTarget:self action:@selector(getcodeMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.codeView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.right.mas_equalTo(-15);
        make.width.mas_equalTo(80);
        make.bottom.mas_equalTo(-5);
    }];
    self.getCodeBtn = btn;
}
- (void)configureData {
    
}

- (void)phoneTextFieldDidChange:(UITextField *)textField {
    if (textField.text.length > 11) {
        textField.text = [textField.text substringToIndex:11];
    }
}

// 获取验证码
- (void)getcodeMethod {
    if (self.phoneTextField.text.length == 0) {
        [self showHint:@"请输入手机号"];
        return;
    }
    if (self.phoneTextField.text.length != 11) {
        [self showHint:@"请输入正确的手机号"];
        return;
    }
    
    NSDictionary *param = @{@"mobile":self.phoneTextField.text};
    [self showHud];
    [TMNetwork requestPostWithParam:param url:@"/user/sendVercode" callback:^(TMBaseReqModel *model) {
        [self hideHud];
        if (model.code == 200) {
            [self showHint:@"验证码发生成功"];
            [self startTimer];
        }else {
            [self showHint:model.message];
        }
    }];
}

- (IBAction)registButtonClick:(UIButton *)sender {
    PBRegistViewController *vc = [[PBRegistViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)loginButtonClick:(UIButton *)sender {
    
    if (self.codeTextField.text.length == 0) {
        [self showHint:@"请输入验证码"];
        return;
    }
    
//    NSString *uuid = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSMutableDictionary *dataDic = [[NSMutableDictionary alloc] init];
    [dataDic setObject:self.phoneTextField.text forKey:@"mobile"];
    [dataDic setObject:self.codeTextField.text forKey:@"code"];
    [dataDic setObject:[NSString stringWithFormat:@"ios%@",[[UIDevice currentDevice] systemVersion]] forKey:@"platform"];
    if ([TMShareData shareData].registrationID) {
        [dataDic setObject:[TMShareData shareData].registrationID forKey:@"device"];
    }else {
        [dataDic setObject:@"" forKey:@"device"];
    }
    
//    NSLog(@"uuid----:%@",uuid);
    
//    NSString *dataJson = [dataDic JSONString];
//    NSLog(@"dataJson = %@",dataJson);
//    NSString *aesData = [PBAES aes256_encrypt:dataJson Encrypttext:@"123456789abcdefg"];
//    NSLog(@"aesData = %@",aesData);

    //公钥
//    NSString *publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDl5RBHD3abOyeYCOLkaWkpJXgJQfMklOWPmdJAnG1eD6CV+UOpUKMy5LtfGHQEM7ao5x3BpMx4MNRUYVwBAmU84PhwNm6xpTJrg5zZCloFmsX+E5ukWE5YFRu8i5+5d8LuQTTTv4XfzbTCTOhON8uj+ypkomETuVNwgRFVFjHd1QIDAQAB";
//    NSString *rsaKey = [RSA encryptString:@"123456789abcdefg" publicKey:publicKey];
    
//    NSLog(@"rsaData = %@",rsaKey);
    [self showHud];
//    NSDictionary *param = @{@"data":dataJson};
    [TMNetwork requestPostWithParam:dataDic url:@"/user/login" callback:^(TMBaseReqModel *model) {
        [self hideHud];
        if (model.code == 200) {
            [kUserDefaults setObject:model.data forKey:@"token"];
//            NSString *token = [kUserDefaults objectForKey:@"token"];
            [[TMNetwork manager].manager.requestSerializer setValue:model.data forHTTPHeaderField:@"user-token"];
//            [self dismissViewControllerAnimated:YES completion:nil];
//            TMTabBarViewController *tabBar = [[TMTabBarViewController alloc] init];
//            [TMShareData shareData].window.rootViewController = tabBar;
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [self showHint:model.message];
        }
    }];
    
}
- (IBAction)forgetButtonClick:(UIButton *)sender {
}

- (void)startTimer {
    __block int time = 60;
    __block UIButton *verifybutton = self.getCodeBtn;
    verifybutton.enabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [verifybutton setTitle:@"获取验证码" forState:UIControlStateNormal];
                verifybutton.enabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *strTime = [NSString stringWithFormat:@"%ds",time];
                [verifybutton setTitle:strTime forState:UIControlStateNormal];
                verifybutton.titleLabel.textColor = [UIColor whiteColor];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - super
- (void)resetNavigationBarItems {
    [super resetNavigationBarItems];
    self.title = @"登录";
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"login_cancel"] style:UIBarButtonItemStyleDone target:self action:@selector(leftItemClick)];
//    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)leftItemClick {
//    [TMShareData shareData].tarBarVC.selectedIndex = 0;
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - other
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
